<template>
  <div class="content">
    <div class="top">
      <ul>
        <li>
          <TextIpt ref="roleName">
            <p>角色名称</p>
          </TextIpt>
        </li>
        <li>
          <GreenBtn @click.native="query">查询</GreenBtn>
          <BlueBtn @click.native="editRole(0)">新增</BlueBtn>
        </li>
      </ul>
    </div>
    <div class="table">
      <el-table :data="filterRole.slice(pages, pages + 10)" border style="width: 100%">
        <el-table-column prop="RoleName" label="角色名称" width="210">
        </el-table-column>
        <el-table-column prop="RoleIntro" label="角色描述" width="260">
        </el-table-column>
        <el-table-column prop="RoleState" label="状态" width="200">
        </el-table-column>
        <el-table-column prop="addman" label="添加人" width="200">
        </el-table-column>
        <el-table-column prop="addDate" label="添加时间" width="300">
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" @click="open(scope.$index, scope.row)">{{ scope.row.RoleState == '停用' ? '启用' :
              '停用' }}</el-button>
            <el-button size="mini" @click="editRole(1, scope.$index, scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="page">
        <div class="total-page">
          <p>共<span>{{ Math.ceil(filterRole.length / 10) }}</span>页/<span>{{ filterRole.length
              }}</span>条数据
          </p>
        </div>
        <el-pagination background layout="prev, pager, next,jumper" @current-change="getPage" :page-size=10
          :current-page.sync=page :total="filterRole.length" hide-on-single-page>
        </el-pagination>
      </div>
    </div>
    <!-- 编辑弹窗 -->
    <el-dialog title="提示" :visible.sync="editDialog" width="45%" :before-close="editClose" class="dialog">
      <el-form ref="editForm" :model="editForm" label-width="80px" :rules="rules">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="editForm.roleIntro"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="roleState">
          <el-radio-group v-model="editForm.roleState">
            <el-radio label="启用"></el-radio>
            <el-radio label="停用"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-tree ref="tree" :data="data" node-key="id" :default-expand-all=true
          :default-checked-keys="editForm.rolePermission" :props="defaultProps" show-checkbox :key="treeKey">
        </el-tree>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="editClose">取 消</el-button>
        <el-button type="primary" @click="editConfirm">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import TextIpt from '@/components/TextIpt.vue';
import GreenBtn from '@/components/GreenBtn.vue';
import BlueBtn from '@/components/BlueBtn.vue';
export default {
  components: {
    TextIpt,
    GreenBtn,
    BlueBtn
  },
  data() {
    return {
      page: 0,
      pages: 0,
      treeKey: 123,
      //被点击的索引
      clickIndex: '',
      titleArr: [
        {
          stair: "首页",
          secondLevel: [{
            name: "工作台",
            path: 'workbench'
          },
          {
            name: "物业大屏",
            path: 'screen'
          }, {
            name: "物业大屏配置",
            path: 'screenconfigue'
          }],
        },
        {
          stair: "智慧物业",
          secondLevel: [
            {
              "name": "房屋管理",
              "path": "buildManagement"
            },
            {
              "name": "楼表盘",
              "path": "towerDial"
            },
            {
              "name": "员工管理",
              "path": "employeeManagement"
            },
            {
              "name": "住户管理",
              "path": "residentManagement"
            },
            {
              "name": "住户确认",
              "path": "residentVerification"
            },
            {
              "name": "团队管理",
              "path": "teamManagement"
            },
            {
              "name": "缴费管理",
              "path": "paymentManagement"
            },
            {
              "name": "投诉建议",
              "path": "complaintsAndSuggestions"
            },
            {
              "name": "维修处理",
              "path": "maintenanceHandling"
            },
            {
              "name": "装修报备",
              "path": "decorationReporting"
            }
          ]
        },
        {
          stair: "内容管理",
          secondLevel: [
            {
              "name": "社区活动",
              "path": "communityActivities"
            },
            {
              "name": "社区公告",
              "path": "communityAnnouncements"
            },
            {
              "name": "广告推荐位",
              "path": "adRecommendationPosition"
            },
            {
              "name": "信息公开",
              "path": "informationDisclosure"
            }
          ]
        },
        {
          stair: "门禁管理",
          secondLevel: [
            {
              "name": "出入记录",
              "path": "accessRecords"
            },
            {
              "name": "门禁权限",
              "path": "doorAccessPermissions"
            },
            {
              "name": "访客管理",
              "path": "visitorManagement"
            },
            {
              "name": "出入二维码",
              "path": "qrCodeAccess"
            },
            {
              "name": "SIM门禁管理",
              "path": "simCardDoorAccessManagement"
            },
            {
              "name": "可视门禁权限",
              "path": "visualDoorAccessPermissions"
            },
            {
              "name": "卡片管理",
              "path": "cardManagement"
            },
            {
              "name": "门禁设备",
              "path": "doorAccessDevices"
            }
          ]

        },
        {
          stair: "视频监控",
          secondLevel: [
            {
              "name": "账号管理",
              "path": "accountManagement"
            },
            {
              "name": "实时监控",
              "path": "realTimeMonitoring"
            },
            {
              "name": "视频回放",
              "path": "videoPlayback"
            },
            {
              "name": "识别记录",
              "path": "recognitionRecords"
            },
            {
              "name": "视频设备",
              "path": "videoDevices"
            },
            {
              "name": "抓拍记录",
              "path": "captureRecords"
            },
            {
              "name": "数据同步",
              "path": "dataSynchronization"
            }
          ]

        },
        {
          stair: "智慧停车",
          secondLevel: [{ "name": "车辆管理", "path": "vehicleManagement" },
          { "name": "停车场管理", "path": "parkingManagement" }]
        },
        {
          stair: "水电气管理",
          secondLevel: [
            { "name": "水表设备", "path": "waterMeterDevices" },
            { "name": "水表告警", "path": "waterMeterAlerts" },
            { "name": "用水情况", "path": "waterUsage" },
            { "name": "水表日用量", "path": "dailyWaterUsage" },
            { "name": "水表充值记录", "path": "waterMeterRechargeRecords" },
            { "name": "电表设备", "path": "electricityMeterDevices" },
            { "name": "用电情况", "path": "electricityUsage" },
            { "name": "电表日用量", "path": "dailyElectricityUsage" },
            { "name": "电表充值记录", "path": "electricityMeterRechargeRecords" }
          ]
        },
        {
          stair: "智能预警",
          secondLevel: [
            { "name": "预警配置", "path": "alertConfiguration" },
            { "name": "布控管理", "path": "controlManagement" },
            { "name": "高空抛物", "path": "overheadObjectThrowing" },
            { "name": "人员预警", "path": "personAlert" },
            { "name": "车辆预警", "path": "vehicleAlert" },
            { "name": "周界入侵", "path": "perimeterIntrusion" },
            { "name": "电瓶车入梯", "path": "electricBikeInElevator" },
            { "name": "消防通道占用", "path": "fireExitOccupation" },
            { "name": "危险犬类识别", "path": "dangerousDogRecognition" }
          ]
        },
        {
          stair: "人员关怀",
          secondLevel: [
            { "name": "关怀对象", "path": "careObjects" },
            { "name": "重点人员关怀", "path": "keyPersonCare" },
            { "name": "关怀告警", "path": "careAlerts" }
          ]
        },
        {
          stair: "智慧防疫",
          secondLevel: [
            { "name": "通行二维码", "path": "accessQrCode" },
            { "name": "电子通行证", "path": "electronicPass" },
            { "name": "通行记录", "path": "accessRecord" },
            { "name": "门磁管理", "path": "doorMagnetManagement" },
            { "name": "门磁告警", "path": "doorMagnetAlerts" }
          ]
        },
        {
          stair: "智慧消防",
          secondLevel: [
            { "name": "烟感设备", "path": "smokeDetectorDevices" },
            { "name": "烟感告警", "path": "smokeDetectorAlerts" }
          ]
        },
        {
          stair: "系统管理",
          secondLevel: [
            { "name": "角色管理", "path": "roleManagement" },
            { "name": "业主权限", "path": "propertyOwnerPermissions" }
          ]
        },
        {
          stair: "活动管理",
          secondLevel: [
            { "name": "卡券管理", "path": "couponManagement" }
          ]
        },
      ],
      data: [{
        id: 1,
        label: '全选',
        children: []
      }],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      editDialog: false,
      editForm: {
        roleName: '',
        roleIntro: "",
        roleState: "",
        rolePermission: [],
        roleID: '',
        selectNode: '',
        addMan: localStorage.getItem('name')
      },
      rules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'change' }
        ],
        roleState: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ]
      },
      roleAll: [],
      filterRole: []
    }
  },
  methods: {
    insertRole() {
      this.$axios.post('http://127.0.0.1/role/insertRole', {
        ...this.editForm
      }, {
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('token')}`,
          'Content-Type': 'application/json' // 如果需要发送 JSON 数据，则包含此行 // 设置请求头
        }
      }).then(res => {
        this.$message({
          message: '添加数据成功',
          type: 'success'
        });
        this.getAllData()
        this.editDialog=false
      }).catch(err => {
        console.log(err);
      })
    },
    //点击查询
    query() {
      this.pages = 0
      this.page = 0
      const serach = {}
      if (this.$refs.roleName.input) {
        serach.roleName = this.$refs.roleName.input
      }
      this.filterRole = this.roleAll.filter(item => {
        if (serach.roleName && !item.RoleName.includes(serach.roleName)) {
          return false;
        }
        return true
      })
    },
    //更新状态
    updateRoleState(str, id) {
      this.$axios.post('http://127.0.0.1/role/updateRoleState', {
        str,
        id
      }, {
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('token')}`,
          'Content-Type': 'application/json' // 如果需要发送 JSON 数据，则包含此行 // 设置请求头
        }
      }).then(res => {
        this.$message({
          message: '修改数据成功',
          type: 'success'
        });
      }).catch(err => {
        console.log(err);
      })
    },
    open(index, row) {
      if (row.ID == 1) {
        this.$message.error('该用户不可操作');
        return
      }
      const str = row.RoleState == '启用' ? '停用' : "启用"
      this.$confirm('此操作将停用/启用, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.updateRoleState(str, row.ID)
        this.filterRole[index + this.pages].RoleState = str
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消操作'
        });
      });
    },
    //get 当前页
    getPage(page) {
      this.pages = 10 * (page - 1)
    },
    //点击编辑
    //indexs用来判断点击是编辑还是新增
    editRole(indexs, index, row) {
      if (indexs) {
        if (row.ID == 1) {
          this.$message.error('该用户不可操作');
          return
        }
        this.editForm.roleName = row.RoleName
        this.editForm.roleIntro = row.RoleIntro
        this.editForm.roleState = row.RoleState
        this.editForm.rolePermission = row.Permission.split(',')
        // 强制更新树组件
        this.treeKey = Date.now();  // 每次修改时改变 key
        this.clickIndex = index + this.pages
        this.editForm.roleID = row.ID
      }
      this.editDialog = true
    },
    editConfirm() {
      this.editForm.selectNode = this.$refs.tree.getCheckedKeys().join(',')
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          //判断点击是编辑还是新增
          if (!this.clickIndex) {
            this.insertRole()
            return
          }
          if (this.editForm.roleID == 1) {
            this.editDialog = false
            return
          }
          let flag = false
          if (this.filterRole[this.clickIndex].RoleName != this.editForm.roleName) {
            this.filterRole[this.clickIndex].RoleName = this.editForm.roleName
            flag = true
          }
          if (this.filterRole[this.clickIndex].RoleIntro != this.editForm.roleIntro) {
            this.filterRole[this.clickIndex].RoleIntro = this.editForm.roleIntro
            flag = true
          }
          if (!(this.filterRole[this.clickIndex].RoleState.includes(this.editForm.roleState))) {
            this.filterRole[this.clickIndex].RoleState = this.editForm.roleState
            flag = true
          }
          if (!(this.filterRole[this.clickIndex].Permission.includes(this.editForm.selectNode))) {
            this.filterRole[this.clickIndex].Permission = this.editForm.selectNode
            flag = true
          }
          if (flag) {
            this.updateRole()
          }
          this.editDialog = false
        } else {
          return false;
        }
      });
    },
    //修改接口
    updateRole() {
      this.$axios.post('http://127.0.0.1/role/editRole', {
        ...this.editForm
      }, {
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('token')}`,
          'Content-Type': 'application/json' // 如果需要发送 JSON 数据，则包含此行 // 设置请求头
        }
      }).then(res => {
        this.$message({
          message: '修改数据成功',
          type: 'success'
        });
      }).catch(err => {
        console.log(err);
      })
    },
    editClose() {
      this.$confirm('确认关闭？')
        .then(_ => {
          this.editDialog = false
        })
        .catch(_ => { });
    },
    getAllData() {
      this.$axios.get('http://127.0.0.1/role/allRole', {
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('token')}`,
          'Content-Type': 'application/json' // 如果需要发送 JSON 数据，则包含此行 // 设置请求头
        }
      }).then(res => {
        this.roleAll = res.data
        this.filterRole = res.data
      }).catch(err => {
        console.log(err);
      })
    }
  },
  mounted() {
    this.getAllData()
    this.titleArr.forEach((item, index) => {
      this.data[0].children.push({ id: item.stair, label: item.stair })
    })
  }
}
</script>

<style scoped>
.page {
  display: flex;
  align-items: center;
  justify-content: end;
  margin-top: 20px;
}

.page>>>button {
  min-width: 35px !important;
  height: 25px;
  line-height: 25px;
  border-radius: 3px !important;
  border: 1px solid rgba(215, 215, 215, 1);
  background: #fff !important;
}

.page>>>.active {
  border-color: rgba(26, 135, 254, 1) !important;
  background-color: rgba(26, 135, 254, 1) !important;
  color: #fff !important;
}

.page>>>.el-pager li {
  min-width: 35px !important;
  height: 25px;
  line-height: 25px;
  border-radius: 3px !important;
  border: 1px solid rgba(215, 215, 215, 1);
  font-size: 12px;
  color: #999;
  font-weight: normal !important;
  background: #fff;
}

.total-page span {
  color: #FF3C2C;
}

.total-page {
  font-size: 12px;
  color: #666;
}

.dialog>>>.el-dialog__body {
  display: flex;
  justify-content: center;
  /* align-items:center; */
  /* flex-direction: column; */
}

.dialog>>>input {
  width: 350px;
}

.table>>>.el-table {
  min-height: 580px;
}
</style>